//
//  ReadLabel.swift
//  reader
//
//  Created by shuguan wang on 2017/4/26.
//  Copyright © 2017年 shuguan wang. All rights reserved.
//

import UIKit
import CoreText
class ReadLabel: UILabel {
    override func drawText(in rect: CGRect) {
        let context:CGContext = UIGraphicsGetCurrentContext()!
        
        // Flip the context coordinates in iOS only.
        context.translateBy(x: 0, y: rect.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        
        let oriString = self.text
        Reader.drawText(oriString!, rect,context)
    }
    static func crackedText(_ size:CGSize,_ text:String)->[String]{
        UIGraphicsBeginImageContext(size)
        var crackedTexts:[String] = []
        let context:CGContext = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        var testText = text
        while !testText.isEmpty {
            let frame = Reader.drawText(testText,CGRect(origin: .zero, size: size),context)
            let frameRange = CTFrameGetVisibleStringRange(frame)
            let currentString = testText[0..<min(frameRange.length, testText.count)]
            crackedTexts.append(currentString)
            testText = testText[min(frameRange.length, testText.count)..<testText.count]
        }
        UIGraphicsEndImageContext()
        return crackedTexts
    }
}

func drawText(_ oriString:String,_ rect:CGRect,_ context:CGContext)->CTFrame {
    var textColor = UIColor.darkText
    if let tc = Preference.textColor,tc.isAscII,tc.count == 6 {
        textColor = UIColor.hex(tc)
    }
    let str = oriString as CFString
    let range = CFRangeMake(0, CFStringGetLength(str))
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.headIndent = 10
    paragraphStyle.tailIndent = rect.size.width - 10
    paragraphStyle.firstLineHeadIndent =  10
    let attr = [kCTForegroundColorAttributeName as String: textColor.cgColor,kCTFontAttributeName as String:CTFontCreateWithName("Helvetica" as CFString, 20, nil),kCTParagraphStyleAttributeName as String: paragraphStyle] as CFDictionary
    let attributedString:CFAttributedString = CFAttributedStringCreate(kCFAllocatorDefault, str, attr)
    let setter = CTFramesetterCreateWithAttributedString(attributedString)
    let frame = CTFramesetterCreateFrame(setter, range,  CGPath(rect: rect, transform: nil), nil)
    CTFrameDraw(frame, context)
    return frame
}
